package com.web.hilover.controller;

import com.web.hilover.entity.*;
import com.web.hilover.service.*;
import com.web.hilover.util.FileUtil;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
    
    @Autowired
    private CoupleService coupleService;
    
    @Autowired
    private TimelineService timelineService;
    
    @Autowired
    private LikeService likeService;
    
    @Autowired
    private CommentService commentService;
    
    @Autowired
    private UserService userService;

    
    @GetMapping("/couple")
    public String userCouple(Model model, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        List<Couple> couples = coupleService.getCouplesByUser(user.getId());
        model.addAttribute("couples", couples);
        return "user/couple";
    }
    
    @GetMapping("/couple/add")
    public String addCouplePage() {
        return "user/couple-add";
    }
    
    @PostMapping("/couple/add")
    @ResponseBody
    public Map<String, Object> addCouple(@RequestParam String lover1Name,
                                        @RequestParam String lover2Name,
                                        @RequestParam String startDate,
                                        @RequestParam(defaultValue = "1") Integer visibility,
                                        @RequestParam(required = false) MultipartFile lover1Avatar,
                                        @RequestParam(required = false) MultipartFile lover2Avatar,
                                        HttpSession session) {
        try {
            User user = (User) session.getAttribute("loginUser");

            String lover1AvatarPath = null;
            String lover2AvatarPath = null;

            if (lover1Avatar != null && !lover1Avatar.isEmpty()) {
                lover1AvatarPath = FileUtil.saveImage(lover1Avatar, "avatar");
            }
            if (lover2Avatar != null && !lover2Avatar.isEmpty()) {
                lover2AvatarPath = FileUtil.saveImage(lover2Avatar, "avatar");
            }

            Couple couple = Couple.builder()
                    .userId(user.getId())
                    .lover1Name(lover1Name)
                    .lover2Name(lover2Name)
                    .lover1Avatar(lover1AvatarPath)
                    .lover2Avatar(lover2AvatarPath)
                    .startDate(Date.valueOf(startDate))
                    .visibility(visibility)
                    .build();
                    
            coupleService.addCouple(couple);
            return Map.of("success", true);
        } catch (Exception e) {
            log.error("添加情侣失败", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }
    
    @GetMapping("/couple/{id}/timeline/add")
    public String addTimelinePage(@PathVariable Long id, Model model) {
        model.addAttribute("coupleId", id);
        return "user/timeline-add";
    }
    
    @PostMapping("/couple/{id}/timeline/add")
    @ResponseBody
    public Map<String, Object> addTimeline(@PathVariable Long id,
                                         @RequestParam String eventDate,
                                         @RequestParam String content,
                                         @RequestParam(required = false) MultipartFile[] images,
                                         HttpSession session) {
        try {
            User user = (User) session.getAttribute("loginUser");
            Couple couple = coupleService.getCoupleById(id);
            
            if (!couple.getUserId().equals(user.getId())) {
                return Map.of("success", false, "message", "无权操作");
            }
            
            List<String> imageUrls = new ArrayList<>();
            if (images != null) {
                for (MultipartFile image : images) {
                    if (!image.isEmpty()) {
                        String imageUrl = FileUtil.saveImage(image, "timeline");
                        imageUrls.add(imageUrl);
                    }
                }
            }
            
            Timeline timeline = Timeline.builder()
                    .coupleId(id)
                    .eventDate(String.valueOf(Date.valueOf(eventDate)))
                    .content(content)
                    .images(String.join(",", imageUrls))
                    .build();
                    
            timelineService.addTimeline(timeline);
            return Map.of("success", true);
        } catch (Exception e) {
            log.error("添加时间轴失败", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }
    
    @GetMapping("/profile")
    public String profile(Model model, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        
        // 获取用户的情侣列表
        List<Couple> couples = coupleService.getCouplesByUser(user.getId());
        
        // 获取用户的点赞记录
        List<Map<String, Object>> likeRecords = likeService.getLikeRecordsByUser(user.getId());
        
        // 获取用户的评论
        List<Map<String, Object>> comments = commentService.getCommentsByUser(user.getId());
        
        model.addAttribute("user", user);
        model.addAttribute("couples", couples);
        model.addAttribute("likeRecords", likeRecords);
        model.addAttribute("comments", comments);
        
        return "user/profile";
    }
    
    @PostMapping("/profile/update")
    @ResponseBody
    public Map<String, Object> updatePassword(@RequestParam String password,
                                       HttpSession session) {
        try {
            if (password == null || password.trim().length() < 6) {
                return Map.of("success", false, "message", "密码长度不能少于6位");
            }
            
            User user = (User) session.getAttribute("loginUser");
            if (user == null) {
                return Map.of("success", false, "message", "用户未登录");
            }
            
            // 调用 service 更新密码
            userService.updatePassword(user.getId(), password.trim());
            
            return Map.of("success", true, "message", "密码修改成功");
        } catch (Exception e) {
            log.error("密码修改失败", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }
    
    @PostMapping("/profile/avatar")
    @ResponseBody
    public Map<String, Object> updateAvatar(@RequestParam MultipartFile avatar,
                                      HttpSession session) {
        try {
            User user = (User) session.getAttribute("loginUser");
            String avatarPath = FileUtil.saveImage(avatar, "avatar");
            
            user.setAvatar(avatarPath);
            userService.updateUser(user);
            
            return Map.of("success", true, "avatar", avatarPath);
        } catch (Exception e) {
            log.error("头像上传失败", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }
    
    @PostMapping("/profile/info")
    @ResponseBody
    public Map<String, Object> updateInfo(@RequestParam String nickname,
                                        @RequestParam(required = false) String email,
                                        @RequestParam(required = false) String bio,
                                        @RequestParam Integer gender,
                                        HttpSession session) {
        try {
            User user = (User) session.getAttribute("loginUser");
            
            // 创建新的用户对象，避免直接修改 session 中的对象
            User updatedUser = new User();
            updatedUser.setId(user.getId());
            updatedUser.setNickname(nickname);
            updatedUser.setEmail(email != null ? email : "");
            updatedUser.setBio(bio != null ? bio : "");
            updatedUser.setGender(gender);
            
            // 更新数据库
            userService.updateUser(updatedUser);
            
            // 更新成功后，重新从数据库获取最新的用户信息
            User refreshedUser = userService.getUserById(user.getId());
            if (refreshedUser != null) {
                session.setAttribute("loginUser", refreshedUser);
                return Map.of("success", true);
            } else {
                return Map.of("success", false, "message", "用户信息更新失败");
            }
        } catch (Exception e) {
            log.error("更新用户资料失败", e);
            return Map.of("success", false, "message", e.getMessage());
        }
    }

} 